package hedron.editor;

import hedron.Activator;
import hedron.Application;
import hedron.db.model.Contact;
import hedron.dialog.ContactsDialog;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;

public class __DemoEditor2 extends FormEditor {
	public static final String ID = "HEDRON.ContactsEditor";

	Table tableDetail;
	Table tableList;

	Listener sortListener;

	Text filterFieldDetail;
	Text filterFieldList;

	String[] sortColumns = { "C_NAME", "C_BULSTAT", "C_MOL", "C_TEL", "TYPE_NAME", "C_TAX", "C_DDS", "C_EMAIL",
			"C_CONTRY", "C_CITY", "C_ADDRESS", "C_BANK", "C_BANKACC" };

	String[] columnNames = { "Име на фирма", "БУЛСТАТ", "МОЛ", "телефон", "Тип", "Данъчен №", "ДДС", "е-маил",
			"Държава", "Град", "Адрес", "Банка", "Сметка №" };
	List<Contact> contacts;

	protected void initTableItem(TableItem item, Contact contact) {
		int i = 0;
		item.setText(i++, contact.C_NAME);
		item.setText(i++, contact.C_BULSTAT);
		item.setText(i++, contact.C_MOL);
		item.setText(i++, contact.C_TEL);
		item.setText(i++, contact.TYPE_NAME);
		item.setText(i++, contact.C_TAX);
		item.setText(i++, contact.C_DDS ? "Да" : "Не");
		item.setText(i++, contact.C_EMAIL);
		item.setText(i++, contact.C_CONTRY);
		item.setText(i++, contact.C_CITY);
		item.setText(i++, contact.C_ADDRESS);
		item.setText(i++, contact.C_BANK);
		item.setText(i++, contact.C_BANKACC);
		item.setText(i++, contact.C_FAX);
	}

	void refresh() {
		if (contacts != null) contacts.clear();
		// contacts = Application.CONTACTS.getContacts("", 200);

		if (tableList != null) {
			tableList.setRedraw(false);
			tableList.removeAll();

			for (Contact contact : contacts) {
				TableItem item = new TableItem(tableList, SWT.NONE);
				initTableItem(item, contact);
			}

			for (int i = 0; i < columnNames.length; i++) {
				tableList.getColumn(i).pack();
			}
			tableList.setRedraw(true);
		}

		if (tableDetail != null) {
			tableDetail.setRedraw(false);
			tableDetail.removeAll();

			for (Contact contact : contacts) {
				TableItem item = new TableItem(tableDetail, SWT.NONE);
				initTableItem(item, contact);
			}

			for (int i = 0; i < columnNames.length; i++) {
				tableDetail.getColumn(i).pack();
			}
			tableDetail.setRedraw(true);
		}
	}

	@Override
	public void init(IEditorSite site, IEditorInput input) throws PartInitException {
		setSite(site);
		setInput(input);
		setTitleImage(Activator.getImage("icons/contacts.png"));
	}

	public void dispose() {
		super.dispose();
	}

	@Override
	protected void addPages() {
		sortListener = new Listener() {
	        public void handleEvent(Event e) {
				if (e.widget instanceof TableColumn) {
				int sortColumn = 0;
				for (; sortColumn < columnNames.length; sortColumn++) {
						if (columnNames[sortColumn].equals(((TableColumn) e.widget).getText())) {
						break;
					}
				}

				tableDetail.setSortColumn((TableColumn)e.widget);
				tableDetail.setSortDirection(SWT.UP);


//	            TableItem[] items = table.getItems();
//	            Collator collator = Collator.getInstance(Locale.getDefault());
//	            TableColumn column = (TableColumn)e.widget;
//	            int index = column == column1 ? 0 : 1;
//	            for (int i = 1; i < items.length; i++) {
//	                String value1 = items[i].getText(index);
//	                for (int j = 0; j < i; j++){
//	                    String value2 = items[j].getText(index);
//	                    if (collator.compare(value1, value2) < 0) {
//	                        String[] values = {items[i].getText(0), items[i].getText(1)};
//	                        items[i].dispose();
//	                        TableItem item = new TableItem(table, SWT.NONE, j);
//	                        item.setText(values);
//	                        items = table.getItems();
//	                        break;
//	                    }
//	                }
//	            }
//	            table.setSortColumn(column);
	        	}
	        }
	    };

	    
		try {
			addPage(new DetailPage());
			addPage(new ListPage());
		} catch (PartInitException e) {
			e.printStackTrace();
		}
		setPageImage(0, Activator.getImage("icons/contacts_red.png"));
		setPageImage(1, Activator.getImage("icons/contacts.png"));
	}

	@Override
	public void doSave(IProgressMonitor monitor) {}

	@Override
	public void doSaveAs() {}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	@Override
	public void setFocus() {
		getActivePageInstance().setFocus();
	}

	public class DetailPage extends FormPage {

		public DetailPage() {
			super(__DemoEditor2.this, "Details", "Detail View");
		}

		@Override
		public void setFocus() {
			if (filterFieldList != null) {
				filterFieldList.setFocus();
			} else {
				super.setFocus();
			}
		}

		protected void createFormContent(IManagedForm managedForm) {
			ScrolledForm form = managedForm.getForm();
			FormToolkit toolkit = managedForm.getToolkit();

			form.setText("Contacts - Detail view");
			form.setBackgroundImage(Activator.getImage("icons/form_background.png"));

			{
				GridLayout layout = new GridLayout();
				layout.numColumns = 1;
				form.getBody().setLayout(layout);
			}

			{// filter section
				Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
				{
					section.setText("Filter");
					section.marginWidth = 0;
					section.marginHeight = 0;
					GridData gdata = new GridData(GridData.FILL_HORIZONTAL);
					section.setLayoutData(gdata);
				}

				{
					Composite grid = toolkit.createComposite(section, SWT.WRAP);
					section.setClient(grid);
					toolkit.paintBordersFor(grid);

					GridLayout layout = new GridLayout();
					layout.numColumns = 3;
					layout.horizontalSpacing = 0;
					grid.setLayout(layout);

					{// cell 1 - search text
						Label label = toolkit.createLabel(grid, "Търсене за : ");
						GridData gdata = new GridData(GridData.BEGINNING, GridData.CENTER, false, false);
						label.setLayoutData(gdata);
					}
					{// cell 2 - search field
						Text text = toolkit.createText(grid, "");
						GridData gdata = new GridData(GridData.FILL, GridData.BEGINNING, true, false);
						text.setLayoutData(gdata);
						text.addKeyListener(new KeyListener() {
							@Override
							public void keyReleased(KeyEvent e) {
								if (e.keyCode == 13) {
									refresh();
								}
								if (filterFieldList != null) {
									filterFieldList.setText(filterFieldDetail.getText());
								}
							}

							@Override
							public void keyPressed(KeyEvent e) {}
						});
						filterFieldDetail = text;
					}
					{// cell 3 - search button
						Button b = toolkit.createButton(grid, "Търси", SWT.PUSH);
						GridData gdata = new GridData(GridData.END);
						gdata.heightHint = 20;
						gdata.widthHint = 70;
						b.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								refresh();
							}
						});
						b.setLayoutData(gdata);
					}
				}

			}

			// splitter section
			SashForm splitter = new SashForm(form.getBody(), SWT.HORIZONTAL);
			{
				GridData gdata = new GridData(GridData.FILL_BOTH);
				splitter.setLayoutData(gdata);
				splitter.setSashWidth(2);
			}

			{// contacts section
				Section section = toolkit.createSection(splitter, Section.TITLE_BAR);
				{
					section.setText("Contacts");
					GridData gdata = new GridData(GridData.FILL_BOTH);
					section.setLayoutData(gdata);
				}

				{
					Composite client = toolkit.createComposite(section, SWT.WRAP);
					section.setClient(client);
					toolkit.paintBordersFor(client);

					GridLayout layout = new GridLayout();
					layout.numColumns = 1;
					client.setLayout(layout);

					{// cell 1
						tableDetail = toolkit.createTable(client, SWT.FULL_SELECTION);
						GridData gdata = new GridData(GridData.FILL_BOTH);
						tableDetail.setLayoutData(gdata);

						for (int i = 0; i < columnNames.length; i++) {
							TableColumn column = new TableColumn(tableDetail, SWT.NONE);
							column.setText(columnNames[i]);
							column.addListener(SWT.Selection, sortListener);
						}
						tableDetail.setHeaderVisible(true);
						tableDetail.setLinesVisible(true);

						tableDetail.setSortColumn(tableDetail.getColumn(0));
						tableDetail.setSortDirection(SWT.UP);
					}
				}
			}

			{// detail section
				Section section = toolkit.createSection(splitter, Section.TITLE_BAR);
				{
					section.setText("Details");
					GridData gdata = new GridData(GridData.FILL_BOTH);
					section.setLayoutData(gdata);
				}

				{// add grid composite in the section
					Composite client = toolkit.createComposite(section, SWT.WRAP);
					section.setClient(client);
					toolkit.paintBordersFor(client);

					GridLayout layout = new GridLayout();
					client.setLayout(layout);

					FormText formText = toolkit.createFormText(client, true);
					GridData gdata = new GridData(GridData.FILL_BOTH);
					formText.setLayoutData(gdata);
					formText.setText("<form><p> <b>bold</b>  &lt; &gt; text а</p></form>", true, false);
				}
			}

			splitter.setWeights(new int[] { 65, 35 });

			{
				Action addAction = new Action("add", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
					public void run() {
						actionAddContact();
					}
				};
				addAction.setToolTipText("Добави нов контрагент");
				addAction.setImageDescriptor(Activator.getImageDescriptor("icons/add.png"));
				form.getToolBarManager().add(addAction);
			}
			{
				Action refreshAction = new Action("refresh", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
					public void run() {
						refresh();
					}
				};
				refreshAction.setToolTipText("Обнови съдържанието");
				refreshAction.setImageDescriptor(Activator.getImageDescriptor("icons/refresh.png"));
				form.getToolBarManager().add(refreshAction);
			}
			form.updateToolBar();
			refresh();
		}
	}

	public class ListPage extends FormPage {

		public ListPage() {
			super(__DemoEditor2.this, "List", "List View");
		}

		@Override
		public void setFocus() {
			if (filterFieldDetail != null) {
				filterFieldDetail.setFocus();
			} else {
				super.setFocus();
			}
		}

		protected void createFormContent(IManagedForm managedForm) {
			ScrolledForm form = managedForm.getForm();
			FormToolkit toolkit = managedForm.getToolkit();

			form.setText("Contacts - List view");
			form.setBackgroundImage(Activator.getImage("icons/form_background.png"));

			{// split form by 2: left site with search-list, right with details
				GridLayout layout = new GridLayout();
				layout.numColumns = 1;
				form.getBody().setLayout(layout);
			}

			{// filter section
				Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
				{
					section.setText("Filter");
					section.marginWidth = 0;
					section.marginHeight = 0;
					GridData gdata = new GridData(GridData.FILL_HORIZONTAL);
					section.setLayoutData(gdata);
				}

				{
					Composite grid = toolkit.createComposite(section, SWT.WRAP);
					section.setClient(grid);
					toolkit.paintBordersFor(grid);

					GridLayout layout = new GridLayout();
					layout.numColumns = 3;
					layout.horizontalSpacing = 0;
					grid.setLayout(layout);

					{// cell 1 - search text
						Label label = toolkit.createLabel(grid, "Търсене за : ");
						GridData gdata = new GridData(GridData.BEGINNING, GridData.CENTER, false, false);
						label.setLayoutData(gdata);
					}
					{// cell 2 - search field
						Text text = toolkit.createText(grid, "");
						GridData gdata = new GridData(GridData.FILL, GridData.BEGINNING, true, false);
						text.setLayoutData(gdata);
						text.addKeyListener(new KeyListener() {
							@Override
							public void keyReleased(KeyEvent e) {
								if (e.keyCode == 13) {
									refresh();
								}
								filterFieldDetail.setText(filterFieldList.getText());
							}

							@Override
							public void keyPressed(KeyEvent e) {}
						});
						filterFieldList = text;
						filterFieldList.setText(filterFieldDetail.getText());
					}
					{// cell 3 - search button
						Button b = toolkit.createButton(grid, "Търси", SWT.PUSH);
						GridData gdata = new GridData(GridData.END);
						gdata.heightHint = 20;
						gdata.widthHint = 70;
						b.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								refresh();
							}
						});
						b.setLayoutData(gdata);
					}
				}

			}

			{// contacts section
				Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
				{
					section.setText("Contacts");
					GridData gdata = new GridData(GridData.FILL_BOTH);
					section.setLayoutData(gdata);
				}

				{
					Composite grid = toolkit.createComposite(section, SWT.WRAP);
					section.setClient(grid);
					toolkit.paintBordersFor(grid);

					GridLayout layout = new GridLayout();
					layout.numColumns = 1;
					grid.setLayout(layout);

					{// cell 1
						tableList = toolkit.createTable(grid, SWT.FULL_SELECTION);
						GridData gdata = new GridData(GridData.FILL_BOTH);
						tableList.setLayoutData(gdata);

						for (int i = 0; i < columnNames.length; i++) {
							TableColumn column = new TableColumn(tableList, SWT.NONE);
							column.setText(columnNames[i]);
							column.addListener(SWT.Selection, sortListener);
						}
						tableList.setHeaderVisible(true);
						tableList.setLinesVisible(true);

						tableDetail.setSortColumn(tableDetail.getColumn(0));
						tableDetail.setSortDirection(SWT.UP);
					}
				}
			}

			{
				Action addAction = new Action("add", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
					public void run() {
						actionAddContact();
					}
				};
				addAction.setToolTipText("Добави нов контрагент");
				addAction.setImageDescriptor(Activator.getImageDescriptor("icons/add.png"));
				form.getToolBarManager().add(addAction);
			}
			{
				Action refreshAction = new Action("refresh", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
					public void run() {
						refresh();
					}
				};
				refreshAction.setToolTipText("Обнови съдържанието");
				refreshAction.setImageDescriptor(Activator.getImageDescriptor("icons/refresh.png"));
				form.getToolBarManager().add(refreshAction);
			}
			form.updateToolBar();
			refresh();
		}
	}

	void actionAddContact() {
		Contact contact = new Contact();
		ContactsDialog dialog = new ContactsDialog(Application.getActiveWorkbench().getShell(), contact);
		dialog.create();
		if (dialog.open() == Window.OK) {
			contact.store();
		}
		refresh();
	}

}